var packModelTable = function() {
	return {
		init : function() {
			var validator;
			var tableId = "pack_model_table";
			//初始化checkBox 初始化行点击选中
			util.initCheckBox(tableId);
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "packModel",
					"value" : $("#id_packModel").val().trim()
				});
				aoData.push({
					"name" : "cellModel",
					"value" : $("#id_batteryCellModel").val().trim()
				});
				aoData.push({
					"name" : "bomEdt",
					"value" : $("#id_bomEdition").val().trim()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#pack_model_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/packModel/getPackModels.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "packModel",
					"bSortable" : false,
					"render" : function(data, type, full, meta) {
						 return '<a class="showDetail" style="cursor:pointer;color:blue;" data-toggle="modal">'+data+'</a>';
					}
				}, 
				{
					"data" : "nominalVoltage",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "nominalCapacity",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "nominalEnergy",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "batteryCellModel",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "bomEdition",
					"bSortable" : false,
					"defaultContent": ""
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});
			
			//窗口关闭时重置内容
			$("#form_btn_close").click(function(e) {
				$("#form_packModelId").val("");
				$("#packModel_form")[0].reset();
				if(validator) {
					$("#packModel_form").validate().resetForm();
				}
			});
			
			// 查询
			$("#btn_query").click(function(e) {
				var table = $('#pack_model_table').DataTable();
				table.draw(true);
			});
			
		    // 重置
			$("#btn_reset").click(function(e) {
				$("#pack_model_form")[0].reset();
			});
			
			//新增
			$("#pack_model_add").click(function(e){
				$('#addModel_title').text('新增电池型号信息');
				util.getDictByParentKey("YYFXDM", 'form_application', '请选择');
				util.getDictByParentKey("DLYYDM", 'form_kineticEnergyApplication', '请选择');
				util.getDictByParentKey("CNYYDM", 'form_energyStorageApplication', '请选择');
				util.getDictByParentKey("ZJCLLXDM", 'form_cathodeMaterialType', '请选择');
				$("#form_kineticEnergyApplication").attr("disabled", true); 
				$("#form_energyStorageApplication").attr("disabled", true);
				$("#add_packModel").modal({show:true,keyboard:false});
			});
			
			// 修改
			$('#pack_model_edit').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("pack_model_table");
				if (d.length != 1) {
					util.showModal('#_alertModal', '请选择一条记录进行操作！')
					return false;
				}
				$('#addModel_title').text('编辑电池型号信息');
				util.getDictByParentKey("YYFXDM", 'form_application', '请选择');
				util.getDictByParentKey("DLYYDM", 'form_kineticEnergyApplication', '请选择');
				util.getDictByParentKey("CNYYDM", 'form_energyStorageApplication', '请选择');
				util.getDictByParentKey("ZJCLLXDM", 'form_cathodeMaterialType', '请选择');
				$.ajax({
					"type" : "post",
					"url" : "main/packModel/getPackModelInfo.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : d[0].pkId
					},
					"success" : function(resp) {
						var model = resp.data;
						if (model) {
							$("#form_packModelId").val(model.pkId);
							$("#form_packModel").val(model.packModel);
							$("#form_nominalVoltage").val(model.nominalVoltage);
							$("#form_nominalCapacity").val(model.nominalCapacity);
							$("#form_nominalEnergy").val(model.nominalEnergy);
							$("#form_singleMaxVol").val(model.singleMaxVol);
							$("#form_singleMinVol").val(model.singleMinVol);
							$("#form_application").val(model.application);
							$("#form_kineticEnergyApplication").val(model.kineticEnergyApplication);
							$("#form_energyStorageApplication").val(model.energyStorageApplication);
							if(model.application=='1'){
								$("#form_kineticEnergyApplication").attr("disabled", false); 
								$("#form_energyStorageApplication").attr("disabled", true);
							} else if(model.application=='2'){
								$("#form_kineticEnergyApplication").attr("disabled", true); 
								$("#form_energyStorageApplication").attr("disabled", false);
							} else {
								$("#form_kineticEnergyApplication").attr("disabled", true); 
								$("#form_energyStorageApplication").attr("disabled", true);
							}
							$("#form_cathodeMaterialType").val(model.cathodeMaterialType);
							$("#form_batteryCellModel").val(model.batteryCellModel);
							$("#form_bomEdition").val(model.bomEdition);
							$("#add_packModel").modal({show:true,keyboard:false});
						} else {
							rmsBox.notify('error', {msg: '数据异常！'});
							return false;
						}
					},
					"error" : function() {
						rmsBox.notify('error', {msg: '数据异常！'});
						return false;
					}
				});
			});
			
			//删除
			$("#pack_model_del").on('click', function(){
				var d = [];
				d = util.getCheckedData("pack_model_table");
				if (d.length == 0) {
					util.showModal('#_alertModal', '请选择要操作的记录！')
				} else {
					util.showModal('#_confirmModal', '您确定要删除选中记录？','_confirmModal_yes')
				}
			});
			
			//确认删除
			$("#_confirmModal").on('click', '#_confirmModal_yes', function(){
				var d = [];
				d = util.getCheckedData("pack_model_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#pack_model_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/packModel/delete.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '删除成功！'});
							table.draw(true);
						} else {
							util.showModal("#_alertModal", "所选记录中包含已被使用的电池型号！");
						}
					}
				});
			});
			
			//查看详情
			$("#pack_model_table").on("click", "a.showDetail",function(e){
				var d = [];
				var id = util.getCheckedData("pack_model_table")[0].pkId;
				$.ajax({
					"type" : "post",
					"url" : "main/packModel/getPackModelDetail.mvc",
					"dataType" : "json",
					async: false, 
					"data" : {
						"pkId" : id
					},
					"success" : function(resp) {
						d = resp;
					}
				});
				
				if (d) {
					$("#pack_model_detail span[id^='info_']").each(function(e){
						var id=$(this).attr("id");
						var idStr = id.substr(5);
						$(this).empty();
						eval("$(this).append(d." +idStr + ")");
						$(this).attr("title",$(this).text());
					});
				} else {
					$("span[id^='info_']").each(function(e){
						var id=$(this).attr("id");
						$("#" + id).empty();
					});
				}
				
				$("#detail_code").text(d.packfactoryCode);
				$("#pack_model_detail").modal({show:true,keyboard:false});
			});
			
			$(function(){
				$('.search-body .my-input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
			
			//保存
			$("#form_model_save").click(function(){
				validator = validateMyForm("packModel_form");
				if(!validator.form()) {
					return false;
				}
				var data = {};
				data['pkId'] = $("#form_packModelId").val();
				data['packModel'] = $("#form_packModel").val();
				data['nominalVoltage'] = $("#form_nominalVoltage").val();
				data['nominalCapacity'] = $("#form_nominalCapacity").val();
				data['nominalEnergy'] = $("#form_nominalEnergy").val();
				data['singleMaxVol'] = $("#form_singleMaxVol").val();
				data['singleMinVol'] = $("#form_singleMinVol").val();
				data['application'] = $("#form_application").val();
				data['kineticEnergyApplication'] = $("#form_kineticEnergyApplication").val();
				data['energyStorageApplication'] = $("#form_energyStorageApplication").val();
				data['cathodeMaterialType'] = $("#form_cathodeMaterialType").val();
				data['batteryCellModel'] = $("#form_batteryCellModel").val();
				data['bomEdition'] = $("#form_bomEdition").val();
				var table = $('#pack_model_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/packModel/saveOrUpdate.mvc",
					"dataType" : "json",
					"data" : data,
					"success" : function(resp) {
						var result = resp.msg;
						if (result == 'repeat') {
							rmsBox.notify('error', {msg: '电池型号已存在！',delay:2000});
						} else {
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#form_btn_close").click();
							table.draw(true);
						}
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '保存失败！',delay:3000});
					}
				});
			});

			/*****************控制单体电压输入值为数字*****************/
			$("#form_singleMaxVol").bind("keypress", function(event) { 
				//debugger 
    			var event= event || window.event;  
    			var getValue = $(this).val();  
			    //控制第一个不能输入小数点"."  
			    if (getValue.length == 0 && event.which == 46) {  
			        //alert(1)  
			        event.preventDefault();  
			        return;  
			    }  
			    //控制只能输入一个小数点"."  
			    if (getValue.indexOf('.') != -1 && event.which == 46) {  
			        event.preventDefault();  
			        //alert(1)  
			        return;  
			    }  
			    //控制只能输入的值  
			    //alert(event.which);
			    if (event.which && (event.which < 48 || event.which > 57) && event.which != 8 && event.which != 46) {  
			        event.preventDefault();  
			        return;  
			    }  
			}); 


			$("#form_singleMinVol").bind("keypress", function(event) { 
				//debugger 
    			var event= event || window.event;  
    			var getValue = $(this).val();  
			    //控制第一个不能输入小数点"."  
			    if (getValue.length == 0 && event.which == 46) {  
			        //alert(1)  
			        event.preventDefault();  
			        return;  
			    }  
			    //控制只能输入一个小数点"."  
			    if (getValue.indexOf('.') != -1 && event.which == 46) {  
			        event.preventDefault();  
			        //alert(1)  
			        return;  
			    }  
			    //控制只能输入的值  
			    //alert(event.which);
			    if (event.which && (event.which < 48 || event.which > 57) && event.which != 8 && event.which != 46) {  
			        event.preventDefault();  
			        return;  
			    }  
			}); 


			$("#form_singleMaxVol").bind("blur", function(event) {
			    var value = $("#form_singleMaxVol").val(), reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/ ;  
			    if (reg.test(value)) {  

			    	$("#form_singleMaxVol").val(value);  
    			} else {
    				$("#form_singleMaxVol").val("");
    			} 
    			
    		});

    		$("#form_singleMinVol").bind("blur", function(event) {
			    var value = $("#form_singleMinVol").val(), reg = /^[0-9]+([.]{1}[0-9]+){0,1}$/ ;  
			    if (reg.test(value)) {  
			    	$("#form_singleMinVol").val(value);  
    			} else {
    				$("#form_singleMinVol").val("");
    			} 
    			
    		});
    		/*****************控制单体电压输入值为数字结束*****************/
    		
			//电池关联管理点击事件
			$("#pack_model_ref").click(function() {
				var model = [];
				model = util.getCheckedData("pack_model_table");
				if (model.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行电池型号关联！");
					return false;
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packModel/initBatteryCorrelation.mvc",
					"dataType" : "json",
					"data" : {id:model[0].pkId},
					"success" : function(data) {
						debugger
						var packModel = data.packModel;
						var multiSelect = data.multiSelect;
						var i = 0;
						$('<select />', {
							 multiple: "multiple",
							 id: "batteryCorrelation_multiSelect",
							 name: "batteryCorrelation_multiSelect[]"
						}).appendTo($('#multiSelect_controls'));
						$.each(multiSelect,function(index,value){
							var selected = "";
							var enable = "";
							var style = "";
							if (multiSelect[index].selected == 'true') {
								i = i + 1;
								selected = " selected ";
							}
							if (multiSelect[index].enable == 'false') {
								enable = "（报废）";
							}
							$('#batteryCorrelation_multiSelect').append('<option value="' + multiSelect[index].packCode+ '" ' + selected + '>'+multiSelect[index].packCode+ enable +'</option>');
		          		});
						$("#batteryCorrelation_packModel").text(packModel.packModel);
						$("#batteryCorrelation_packModel").attr("title", packModel.packModel);
						$("#batteryCorrelation_packNum").text(i);
						$("#batteryCorrelation_pkId").val(packModel.pkId);
						
						initMultiSelect("#batteryCorrelation_multiSelect");
						$("#batteryID-correlation").modal({show:true, keyboard:false});
					},
					"error" : function(resp) {
						util.showModal("#_alertModal", "获取该型号电池关联信息失败！");
					}
				});
			});
			
			//电池绑定注册保存按钮点击事件
			$("#batteryCorrelation_save").click(function() {
				var packModel = {};
				packModel['pkId'] = $("#batteryCorrelation_pkId").val();
				var packCodeList = $("#batteryCorrelation_multiSelect").val();
				var packCodeStr = "";
				if (!util.isEmpty(packCodeList)) {
					$.each(packCodeList, function(index,value){
						if (index == 0) {
							packCodeStr = packCodeList[index];
						} else {
							packCodeStr += "," + packCodeList[index];
						}
						
	          		});
				}
				packModel['packCode'] = packCodeStr;
				var table = $('#pack_model_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/packModel/saveBatteryCorrelation.mvc",
					"dataType" : "json",
					"data" : packModel,
					"success" : function(resp) {
						$("#batteryCorrelation_close").click();
						table.draw(true);
						rmsBox.notify('success', {msg: '操作成功！'});
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '操作失败！',delay:3000});
					}
				});
			});

			
			//电池绑定注册取消按钮点击事件
			$("#batteryCorrelation_close").click(function() {
				$('#multiSelect_controls').html("");
			});
			
			//模态框关闭清空多选插件
			$("#batteryID-correlation").on('click', '.close', function(e) {
				e.preventDefault();
				$('#multiSelect_controls').html("");
			});
			//初始化两边多选择插件
			function initMultiSelect(selector) {
				$(selector).multiSelect({
				  selectableHeader: "<input type='text' style='width:205px;' autocomplete='off' placeholder='搜索...'>",
				  selectionHeader: "<input type='text' style='width:205px;' autocomplete='off' placeholder='搜索...'>",
				  afterInit: function(ms){
				    var that = this,
				        $selectableSearch = that.$selectableUl.prev(),
				        $selectionSearch = that.$selectionUl.prev(),
				        selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',
				        selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected';
				    that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
				    .on('keydown', function(e){
				      if (e.which === 40){
				        that.$selectableUl.focus();
				        return false;
				      }
				    });

				    that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
				    .on('keydown', function(e){
				      if (e.which == 40){
				        that.$selectionUl.focus();
				        return false;
				      }
				    });
				  },
				  afterSelect: function(){
				    this.qs1.cache();
				    this.qs2.cache();
				  },
				  afterDeselect: function(){
				    this.qs1.cache();
				    this.qs2.cache();
				  }
				});
			};

			function validateMyForm(formId){
				return $( '#' + formId ).validate({
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	packModel:{
			        		'required':true
			        	}
			        },
			        messages:{  
			        	packModel:{
			        		required :'不能为空'
			        	}
			        }, 
			        errorPlacement: function (error, element) { 
			        	//默认以span形式显示在输入框后
			           error.insertAfter(element);
			           $(element.next()).attr('title', $(error).text()).tooltip();
			           $(error).text('');
			        }
			    });
			}
			
			/*
			 * 应用方向change事件
			 * 1、choose 动力  则动力启用 储能禁用
			 * 2、choose 储能 则储能启用 动力禁用
			 * 3、choose 其他 则储能 动力都禁用
			 */
			$("#form_application").change(function(){
				if(this.value=='1'){
					//动力
					$("#form_kineticEnergyApplication").attr("disabled", false); 
					$("#form_energyStorageApplication option:first").prop("selected", 'selected');  
					$("#form_energyStorageApplication").attr("disabled", true);
				}else if (this.value == '2'){
					//储能
					$("#form_energyStorageApplication").attr("disabled", false);
					$("#form_kineticEnergyApplication option:first").prop("selected", 'selected');
					$("#form_kineticEnergyApplication").attr("disabled", true); 
				} else{
					$("#form_kineticEnergyApplication option:first").prop("selected", 'selected');
					$("#form_energyStorageApplication option:first").prop("selected", 'selected');
					$("#form_kineticEnergyApplication").attr("disabled", true); 
					$("#form_energyStorageApplication").attr("disabled", true);
				}
				
			});
		}
	};
}();

